<template>
  <view>
    <u-modal v-model="show" :content="content"></u-modal>
    <u-form :model="courseFile" ref="uForm" style="margin: 0 20rpx">
      <u-form-item label="*目录" prop="courseCatalogId"
        ><u-input
          v-model="courseCatalogName"
          type="select"
          @click="catalogShow = true"
      /></u-form-item>
      <u-form-item label="*标题" prop="name"
        ><u-input v-model="courseFile.name"
      /></u-form-item>
    </u-form>
    <view class="choose-btn">
      <u-button
        @click="postCourseFile"
        type="success"
        :ripple="true"
        size="medium"
        >选择文件</u-button
      >
    </view>
    <view style="text-align: center; margin-top: 20rpx">
        <u-button
          size="medium"
          shape="circle"
          type="primary"
          @click="submit"
          :ripple="true"
          ripple-bg-color="#a0cfff"
          >提交</u-button
        >
      </view>
    <u-select
      v-model="catalogShow"
      mode="single-column"
      :list="list"
      value-name="id"
      label-name="name"
      @confirm="catalogConfirm"
    ></u-select>
  </view>
</template>

<script>
import { getUploadUrl } from "../../utils/constants";
import { getToken } from "../../common/auth";

export default {
  data() {
    return {
      show: false,
      content: "上传资料请进入网页版",
      id: "",
      url: getUploadUrl(),
      courseFile: {
        courseCatalogId: "",
        name: "",
        courseId: "",
        path: ''
      },
      courseCatalogName: "",
      rules: {
        courseCatalogId: [
          {
            required: true,
            message: "目录不能为空",
            trigger: "blur",
          },
        ],
        name: [
          {
            required: true,
            message: "标题不能为空",
            trigger: "blur",
          },
        ],
      },
      catalogShow: false,
      list: [],
      tempFiles: []
    };
  },
  // 必须要在onReady生命周期，因为onLoad生命周期组件可能尚未创建完毕
  onReady() {
    this.$refs.uForm.setRules(this.rules);
  },
  async onLoad(e) {
    this.id = e.id;
    this.courseFile.courseId = e.id;
    const res = await this.$u.api.getCatalogByCourseId(e.id, { pageNum: 1 });
    this.list = res.data;
  },
  methods: {
    submit(){
      this.upload(this.tempFiles);
    },
    catalogConfirm(e) {
      this.courseFile.courseCatalogId = e[0].value;
      this.courseCatalogName = e[0].label;
    },
    postCourseFile() {
      //#ifndef H5
      this.show = true;
      // #endif
      //#ifdef H5

      uni.chooseFile({
        count: 1, //默认100
        extension: [".doc", ".xlsx", ".docx", ".ppt", ".pptx", ".xls"],
        success: (res) => {
          this.tempFiles = res.tempFiles;
          this.courseFile.name = this.tempFiles[0].name;
        },
        fail: (err) => {
          console.log("出错信息", err);
          this.$u.toast("选择文件出错！");
        },
      });
      //#endif
    },
    upload(tempFiles) {
      const that = this;
      for (let item of tempFiles) {
        if (item.size < 70 * 1024 * 1024) {
          console.log(item.path);
          uni.uploadFile({
            url: this.url, //仅为示例，非真实的接口地址
            filePath: item.path,
            header: {
              Authorization: getToken()
            },
            name: "file",
            success: (res) => {
              const data = JSON.parse(res.data);
              if(data.code == 401){
                that.$u.route('/pages/login/login')
                return;
              }
              this.courseFile.path = data.data.fullPath
              that.save();
            },
          });
        } else {
          this.$u.toast(item.name + "已超出规定大小，建议拆分为两个上传");
        }
      }
    },
    save(){
      this.$refs.uForm.validate((valid) => {
        if (valid) {
          this.$u.api.createCourseFile(this.courseFile).then((res) => {
            if (res.code === 200) {
              uni.$emit("courseFileRefresh");
              // #ifndef H5
              uni.navigateBack({
                delta: 1,
              });
              // #endif
              // #ifdef H5
              history.back();
              // #endif
            }
          });
        }
      });
    }
  },
};
</script>

<style lang="scss">
.choose-btn {
  text-align: center;
  margin-top: 40rpx;
}
</style>
